package com.alex.tkmybatis.common.db;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class Dbconfig {

    @Value("${spring.datasource.url}")
    private String jdbcUrl;

    @Value("${spring.datasource.username}")
    private String jdbcUser;

    @Value("${spring.datasource.password}")
    private String jdbcpwd;

    //  打印SQL的,使用这个数据源
    @Bean("dataSource")
    @Primary
    public DataSource dataSource() {
        DataSource dataSource = null;
        dataSource = HikariDataSource();
        return dataSource;

    }

    private HikariDataSource HikariDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUsername(jdbcUser);
        dataSource.setPassword(jdbcpwd);
        dataSource.setMaximumPoolSize(20);
        dataSource.setMinimumIdle(5);
        dataSource.setAutoCommit(true);
        dataSource.setMaxLifetime(1800000);
        dataSource.setIdleTimeout(300000);
        dataSource.setConnectionTimeout(300000);
        dataSource.setConnectionTestQuery("Select 1 from dual");
        System.out.println("use HikariDataSource success===========");
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
